﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace Wicresoft.Task.ARNotice
{
    /// <summary>
    /// 简单模板引擎，使用正则表达式替换模板中{文字}
    /// 周平(parkerz@wicresoft.com)开发和维护
    /// </summary>
    class SimpleTemplateEngine
    {
        private string template;
        private object[] entities;

        public void ProceedTemplate(string template, params object[] entities)
        {
            if (entities == null || entities.Length == 0)
                throw new ArgumentException("entities cannot be null or empty.");

            this.template = template;
            this.entities = entities;

            InitTemplateInternal();
        }

        private void InitTemplateInternal()
        {
            Dictionary<string, string> dict = BuildParameters();
            StringBuilder buffer = new StringBuilder(template);

            //
            string value;
            string tmpText = buffer.ToString();

            foreach (Match match in Regex.Matches(tmpText, "{[^:}]+}"))
            {
                if (dict.TryGetValue(match.Value.Trim('{', '}'), out value))
                {
                    //value is the value
                    buffer.Replace(match.Value, value);
                }
            }

            //
            ProcessedText = buffer;
        }

        private Dictionary<string, string> BuildParameters()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();

            foreach (var entity in entities)
            {
                foreach (var prop in entity.GetType().GetProperties())
                {
                    var value = prop.GetValue(entity, null);
                    dict.Add(prop.Name, value == null ? "" : value.ToString());
                }
            }

            return dict;
        }

        public StringBuilder ProcessedText { get; private set; }
    }
}
